/**
 * 公共类集合
 */
const config = require('../../config/config');
class HelperExtend {
    /**
    * 成功
    * @param {*} msg 
    * @param {*} data 
    * @param {*} code 
    */
    static async success(data = {}, msg = 'SUCCESS', code = 1000) {
        return { code: code, msg: msg, data: data };
    }
    /**
     * 错误
     * @param {*} msg 
     * @param {*} data 
     * @param {*} code 
     */
    static async error(data = {}, msg = 'ERROR', code = 4003) {
        return { code: code, msg: msg, data: data };
    }
    //获取当前时间日期格式
    static async getTime() {
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();
        let time = (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
        return time;
    }
    //查询对应的配置信息
    static async configData(key, value) {
        return config[key][value]
    }
    static async getLog(str) {
        console.log('-------------------------------------');
        console.log(str);
        console.log('-------------------------------------');
    }
    //获取ip
    static async getIp(request) {
        let ip = request.headers['x-forwarded-for'] || request.ip || request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress || '';
        if (ip.split(',').length > 0) {
            ip = ip.split(',')[0];
        }
        return ip;
    }
    /**
     * 从数组中随机取出几个元素
     * @param {*} arr 
     * @param {*} count 
     */
    static async getRandomArrayElements(arr, count) {
        let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
        while (i-- > min) {
            index = Math.floor((i + 1) * Math.random());
            temp = shuffled[index];
            shuffled[index] = shuffled[i];
            shuffled[i] = temp;
        }
        return shuffled.slice(min);
    }
    /**
     * json按照某个值排序
     * @param {排序字段} key 
     * @param {true：反，false:正} sortType 
     */
    static async keysort(key, sortType) {
        return function (a, b) {
            return sortType ? (a[key] < b[key]) : (a[key] > b[key])
        }
    }
    /**
     * 将json转换成无任何符号的字符串和转化的json
     * @param {*} paramData 
     */
    static async jsonGetString(paramData) {
        let str = "";
        let json = {};
        for (let i = 0; i < paramData.length; i++) {
            let key = paramData[i]['key'];
            json[key] = paramData[i]['value'];
            str += key + json[key];
        }
        return [str, json];
    }
    static async trim(str) {
        return str.trim();
    }
    
}
module.exports = HelperExtend;